<template>
    <!-- 新增共享文件弹窗 -->
    <el-dialog :title="'新增共享文件'" :visible.sync="visible" :close-on-click-modal="false" @close="onClose"
        style="height: 600px;" :lock-scroll="false" :before-close="onBeforeClose">
        <template v-if="fileDataList && fileDataList.length !== 0">
            <el-table :data="fileDataList" style="width: 100%" height="300">
                <el-table-column type="index" label="#" width="52">
                </el-table-column>
                <el-table-column prop="originalName" label="文件名" width="180">
                </el-table-column>
                <el-table-column prop="url" label="资源位置" width="180">
                </el-table-column>
                <el-table-column prop="path" label="路径">
                </el-table-column>
                <el-table-column label="共享给" width="200" fixed="right">
                    <template slot-scope="scope">
                        <el-select v-model="scope.row.shareIds" multiple placeholder="选择一个或多个对象" filterable size="mini"
                            @change="handleRowSupplierSelectChange">
                            <el-option v-for="item in selectMailUsers" :key="item.key"
                                :label="item.key === loginUserId?item.label+' 不能分享给自己':item.label" :value="item.key"
                                :disabled="item.key === loginUserId">
                            </el-option>
                        </el-select>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="100" fixed="right">
                    <template slot-scope="scope">
                        <el-button size="small" plain type="danger" icon="el-icon-delete"
                            @click="handleRowDelete(scope.row)" v-hasPermi="['fileshare:index:add']"
                            style="padding: 5px;">移除
                        </el-button>
                    </template>
                </el-table-column>
            </el-table>
        </template>
        <template v-else>
            <p>请在下方上传要共享的文件。</p>
            <p>注意：文件大小最大不超过<span class="warn">128MB</span>，最少要上传<span class="warn">1个</span>文件，最多可上传<span
                    class="warn">10个</span>文件。</p>
            <p>支持的上传文件格式：<span class="warn">{{ this.fileType.join(',') }}</span></p>
        </template>
        <el-upload multiple :action="uploadFileUrl" :before-upload="handleBeforeUpload" :file-list="fileList"
            :limit="limit" :on-error="handleUploadError" :on-exceed="handleExceed" :on-success="handleUploadSuccess"
            :show-file-list="false" :headers="headers" class="upload-file-uploader" ref="fileUpload"
            style="margin-top: 5px;">
            <el-button size="mini" type="primary">上传文件</el-button>
        </el-upload>
        <div style="width:100%;text-align: center;">
            <el-button type="primary" @click="onSubmit">提交</el-button>
            <el-button @click="onClose" :disabled="cancelDisabled">取消</el-button>
        </div>
    </el-dialog>
</template>

<script>
import request from '@/utils/request'
import { getToken } from "@/utils/auth";
import { watch } from 'vue';

export default {

    name: "addtionDialog",
    props: {
        dialogVisible: {
            type: Boolean,
            default: false
        }
        ,loginUserId:{
            type:Number
            ,default:0
        }
    }
    , data() {
        return {
            form: {
                originalName: ''
                , url: ''
                , path: ''
            }
            , fileDataList: []
            , isEdit: true
            , uploadFileUrl: process.env.VUE_APP_BASE_API + "/common/upload"
            , visible: this.dialogVisible
            , isDataModify: false
            , fileType: ["doc", "docx", "xls", "xlsx", "ppt", "pptx",
                "txt", "pdf", "png", "jpg", "jpeg", "pdf", "cad", "bmp", 
                "gif", "svg", "log", "html", "xml", "json", "md", "zip", "rar","gz", "bz2"]
            , fileSize: 128
            , limit: 10
            , number: 0
            , fileList: []
            , headers: {
                Authorization: getToken()
            }
            , isSubmit: false
            , cancelDisabled: false
            , selectMailUsers: []
            ,userChargeSupplierList:[]
        }
    }
    , methods: {
        onBeforeClose(done) {
            if (this.fileDataList.length !== 0) {
                this.$modal.confirm('你有上传数据未提交，关闭窗口后数据将会永久丢失，是否确认关闭窗口?')
                    .then(() => {
                        done();
                    }).catch(e => { });
            } else {
                done();
            }
        }
        , onClose() {
            this.visible = false;
            this.$emit('close', this.isDataModify);
        }
        , onSubmit() {
            this.submitRequest().then(res => {
                if (res.code === 200) {
                    this.isDataModify = true;
                    this.fileDataList = [];
                    this.$modal.msgSuccess('新增成功');
                    this.onClose();
                } else {
                    this.$modal.msgError(res.msg);
                }
            }).catch(err => {
                console.log(err);
            }).finally(() => {
                this.toggleButtons();
            })
        }
        , submitRequest() {
            this.toggleButtons();
            return request({
                url: '/file-share/add'
                , method: 'post'
                , data: this.fileDataList
            })
        }
        , toggleButtons() {
        }
        // 上传前校检格式和大小
        , handleBeforeUpload(file) {
            // 校检文件类型
            const fileName = file.name.split('.');
            const fileExt = fileName[fileName.length - 1];
            if (!fileExt || fileExt.length === 0) {
                this.$modal.msgError('文件格式不正确，未知文件格式。');
                return false;
            }
            const isTypeOk = this.fileType.indexOf(fileExt.toLowerCase()) >= 0;
            if (!isTypeOk) {
                this.$modal.msgWarning(`文件格式不正确，请上传指定格式文件。`);
                return false;
            }
            // 校检文件大小
            const isLt = file.size / 1024 / 1024 < this.fileSize;
            if (!isLt) {
                this.$modal.msgError(`上传文件大小不能超过 ${this.fileSize} MB。`);
                return false;
            }
            this.$modal.loading("正在上传文件，请稍候...");
            this.number++;
            return true;
        }
        // 文件个数超出
        , handleExceed() {
            this.$modal.msgError(`上传文件数量不能超过 ${this.limit} 个!`);
        },
        // 上传失败
        handleUploadError(err) {
            this.$modal.msgError("上传文件失败，请重试");
            this.$modal.closeLoading();
        },
        // 上传成功回调
        handleUploadSuccess(res, file) {
            this.$modal.closeLoading();
            if (res.code === 200) {
                // this.cancelDisabled = true;
                this.fileDataList.push({
                    originalName: file.name,
                    url: res.url,
                    path: res.path
                    , shareIds: this.userChargeSupplierList.map(item=>item)
                });
                this.$modal.closeLoading();
            } else {
                this.number--;
                this.$modal.msgError(res.msg);
            }
        }
        , handleRowDelete(row) {
            this.fileDataList.splice(this.fileDataList.indexOf(row), 1);
            this.number--;
        }
        , getMailUsers() {
            request({
                url:'/system/user/list'
                , method: 'get'
                , params: { pageNum: 1, pageSize: 99999 }
            })
                .then(res => {
                    this.selectMailUsers = [];
                    if (res.rows && res.rows.length !== 0) {
                        var supplierUsers = this.getSupplierUidData();
                        for (let it of res.rows) {
                            // 判断是否是供应商用户
                            if (supplierUsers.indexOf(it.userId) === -1) {
                                continue;
                            }
                            this.selectMailUsers.push({
                                key: it.userId,
                                label: it.userName + ' (' + it.nickName+')',
                            })
                        }
                    }
                })
                .catch(err => console.log(err))
        }
        , handleRowSupplierSelectChange(datas){
        }
        ,getUserChargeSupplierList(){
            this.$modal.loading("正在加载数据...");
            request({
                url:'/file-share/user-charge-supplier-list'
               , method: 'get'
            })
            .then(res=>{
                if(res.code===200&&res.data.length!==0){
                    this.userChargeSupplierList = res.data.map(item=>{
                        return Number(item.sysUserId);
                    });

                }
            })
            .catch(err=>{
               console.log(err);
            })
            .finally(()=>{
               this.$modal.closeLoading(); 
            })
        }
        ,getSupplierUidData(){
            var listStr = localStorage.getItem('supplier-list');
            // 判断listStr是否为空
            if (listStr&&listStr.length!==0) {
                // 将字符串转换为数组
                return JSON.parse(listStr).map(item => Number(item.sysUserId)); 
            }
            return [];
        }

    }
    , mounted() {
        this.getMailUsers();
        this.getUserChargeSupplierList();
    }
    ,watch:{
        fileDataList(newVa,old){
            if (newVa.length===0){
                this.cancelDisabled = false;
            }else{
                this.cancelDisabled = true;
            }            
        }
    }
}
</script>

<style scoped>
.warn{
    color: #E6A23C;
    text-decoration: underline;
}
</style>